﻿using System.Collections;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web;
using System;
using System.IO;
using ASPNETVN.PORTAL.Components.Configuration;
using ASPNETVN.PORTAL.Components.Helpers;

namespace ASPNETVN.PORTAL.Modules.GALLERY.Components
{
    public class GALLERYUpload : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.Files.Count > 0)
            {
                Guid mid = new Guid(context.Request.QueryString["mid"]);
                Hashtable ht = PortalConfiguration.GetModuleSettings(mid);
                string uploadPath = ht["UploadPath"].ToString();

                // Get the applications path.
                string tempFile = context.Request.PhysicalApplicationPath;
                
                // Loop through all the uploaded files.
                for (int j = 0; j < context.Request.Files.Count; j++)
                {
                    // get the current file
                    HttpPostedFile uploadFile = context.Request.Files[j];
                    // if there was a file uploded
                    if (uploadFile.ContentLength > 0)
                    {
                        int collectionID = 0;
                        if (context.Request.QueryString["ItemID"] != null)
                        {
                            try
                            {
                                collectionID = Convert.ToInt32(context.Request.QueryString["ItemID"]);                                
                            }
                            catch
                            {
                                collectionID = 0;
                            }
                        }

                        if (collectionID > 0)
                        {
                            string physicalDirectory = string.Format("{0}{1}", tempFile, uploadPath + "\\" + context.Request.QueryString["mid"]);
                            string physicalThumbnailDirectory = string.Format("{0}{1}", tempFile, uploadPath + "\\" + context.Request.QueryString["mid"]) + "\\Thumbnails\\";
                            
                            // Tạo thư mục để chứa images.
                            if (Directory.Exists(physicalDirectory) == false)
                            {
                                Directory.CreateDirectory(physicalDirectory);
                            }

                            // Tạo thư mục để chứa thumbnail images.
                            if (Directory.Exists(physicalThumbnailDirectory) == false)
                            {
                                Directory.CreateDirectory(physicalThumbnailDirectory);
                            }


                            string physicalPath = physicalDirectory + "\\" + uploadFile.FileName;
                            string physicalThumbnailPath = physicalThumbnailDirectory + "\\" + uploadFile.FileName;

                            int i = 1;
                            while (File.Exists(physicalPath))
                            {
                                physicalPath = physicalDirectory + "\\" + i + "_" + uploadFile.FileName;
                                physicalThumbnailPath = physicalThumbnailDirectory + "\\" + i + "_" + uploadFile.FileName;
                                i++;
                            }

                            // Lưu image.
                            uploadFile.SaveAs(physicalPath);

                            // Tạo thumbnail image.
                            Image fullPicture;
                            try
                            {
                                // Chỉnh kích thước thumbnail image từ image.
                                fullPicture = new Bitmap(physicalPath);
                                Image thumbnail = ImageHelper.ResizeImage(fullPicture, 120, 80, ImageResizeOption.MaintainAspectWidth);
                                fullPicture.Dispose();

                                // Chỉnh kích thước mới cho image.
                                fullPicture = new Bitmap(physicalPath);
                                Image original = ImageHelper.ResizeImage(fullPicture, 640, 480, ImageResizeOption.MaintainAspectWidth);
                                fullPicture.Dispose();

                                // Xóa image vừa upload, chỉ lấy image đã chỉnh kích cỡ.
                                if (File.Exists(physicalPath))
                                {
                                    File.Delete(physicalPath);
                                }
                                
                                string ext = uploadFile.FileName.Substring(uploadFile.FileName.LastIndexOf('.'));
                                switch (ext.ToLower())
                                {
                                    case ".jpg":
                                        thumbnail.Save(physicalThumbnailPath, ImageFormat.Jpeg);
                                        original.Save(physicalPath, ImageFormat.Jpeg);
                                        break;
                                    case ".png":
                                        thumbnail.Save(physicalThumbnailPath, ImageFormat.Png);
                                        original.Save(physicalPath, ImageFormat.Png);
                                        break;
                                    case ".gif":
                                        thumbnail.Save(physicalThumbnailPath, ImageFormat.Gif);
                                        original.Save(physicalPath, ImageFormat.Gif);
                                        break;
                                    case ".bmp":
                                        thumbnail.Save(physicalThumbnailPath, ImageFormat.Bmp);
                                        original.Save(physicalPath, ImageFormat.Bmp);
                                        break;
                                }
                                thumbnail.Dispose();
                                original.Dispose();                                
                            }
                            catch (Exception ex)
                            {
                                throw new Exception("Error in create thumbnail: " + ex.Message);
                            }

                            // Lưu thông tin vào CSDL.
                            Picture picture = new Picture();
                            picture.CollectionID = collectionID;
                            string filename = physicalPath.Substring(physicalPath.LastIndexOf('\\') + 1);
                            picture.FileName = filename;
                            picture.Insert();
                        }
                    }
                }
            }
            HttpContext.Current.Response.Write(" ");
        }

        #endregion
    }
}